#!/bin/sh

if [ ${#SERVER} -lt 10 ]; then
    SERVER=http://ovpnpkg.googlecode.com/svn/trunk
fi

echo '#!/bin/sh
success=0
while [ $success -eq 0 ]
do
    echo Downloading $1/$2
    wget $1/$2
    if [ -f $2 ]; then
        success=1
    fi
done

if [ "$3" == "yes" ]; then
    chmod +x $2
fi' > downfile.sh
    
chmod +x downfile.sh

./downfile.sh $SERVER 'libcrypto.so.0.9.8'
./downfile.sh $SERVER 'liblzo2.so.2.0.0'
./downfile.sh $SERVER 'libssl.so.0.9.8'
./downfile.sh $SERVER 'openvpn' 'yes'
./downfile.sh $SERVER 'tun.o'
./downfile.sh $SERVER 'ip-up.sh' 'yes'
./downfile.sh $SERVER 'ip-down.sh' 'yes'
./downfile.sh $SERVER 'chnroutes.txt'

killall openvpn

if [ -f start.pid ]; then
    exit 0
fi

echo $$ > start.pid

# Check network connection
ret=`ping -c 1 8.8.8.8 | grep "1 packets received"`
while [ ${#ret} -lt 10 ]
do  
    sleep 30
    ret=`ping -c 1 8.8.8.8 | grep "1 packets received"`
done

# Start generate openvpn configuration
rm ovpn.conf
touch ovpn.conf

# Use chnroutes
if [ "$2" == "yes" ]; then
    cat chnroutes.txt   >> ovpn.conf
fi

if [ "$1" == "cert" ]; then
    echo cert client.crt    >> ovpn.conf
    echo key client.key     >> ovpn.conf
else
    echo auth-user-pass userpass.txt    >> ovpn.conf
    echo auth-nocache                   >> ovpn.conf
fi

cat openvpn.conf    >> ovpn.conf
echo ca ca.crt      >> ovpn.conf
echo up /tmp/openvpn/ip-up.sh       >> ovpn.conf
echo down /tmp/openvpn/ip-down.sh   >> ovpn.conf

export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH
if [ "$3" == "debug" ]; then
    echo log openvpn.log    >> ovpn.conf
fi
./openvpn --daemon --config ovpn.conf

rm start.pid